package com.xywl.escort.view.order.delivery

import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.DeliveryDetailAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.ProjectDeliveryDetailResp
import com.xywl.escort.bean.ProjectLogisticsResp
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.GlideApp
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_delivery_detail.*
import kotlinx.android.synthetic.main.view_delivery_footer.*
import kotlinx.android.synthetic.main.view_delivery_footer.view.*
import kotlinx.android.synthetic.main.view_delivery_header.*
import kotlinx.android.synthetic.main.view_delivery_header.view.*
import timber.log.Timber
import java.util.*
import javax.inject.Inject

/**
 * 发货详情
 */
@Route(path = "/xy/order/delivery/detail")
class DeliveryDetailActivity : BaseActivity(), DeliveryDetailContract.View {
    private lateinit var mAdapter: DeliveryDetailAdapter
    private lateinit var headerView: View
    private lateinit var footerView: View
    private val list = ArrayList<String>()

    @Inject
    lateinit var mPresenter: DeliveryDetailContract.Presenter

    @Autowired
    @JvmField
    var id = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_delivery_detail)
        ARouter.getInstance().inject(this)

        initView()
        initData()
        addListener()
    }

    private fun initView() {
        showBackButton()
        setTitleText(R.string.order_detail)
        val manager = GridLayoutManager(this, 2)
        recycler_spec.layoutManager = manager

        mAdapter = DeliveryDetailAdapter(R.layout.item_delivery_spec, list)
        headerView = layoutInflater.inflate(R.layout.view_delivery_header, recycler_spec.parent as ViewGroup, false)
        footerView = layoutInflater.inflate(R.layout.view_delivery_footer, recycler_spec.parent as ViewGroup, false)
        mAdapter.addHeaderView(headerView)
        mAdapter.addFooterView(footerView)
        recycler_spec.adapter = mAdapter
    }

    private fun initData() {
        mPresenter.takeView(this)
        mPresenter.loadDetail(id)
    }

    private fun addListener() {
        btn_delete_order.setOnClickListener {
            mPresenter.delete(id)
        }
        btn_order_remind.setOnClickListener {
            mPresenter.remind(id)
        }
        btn_order_confirm_receipt.setOnClickListener {
            mPresenter.confirmReceipt(id)
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun loadSuccess(dataBean: ProjectDeliveryDetailResp.DataBean?) {
        val standSmallNames = dataBean!!.standSmallNames
        if (!TextUtils.isEmpty(standSmallNames)) {
            val strings = standSmallNames.split(",")
            for (values in strings) {
                list.add(values)
            }
            mAdapter.setNewData(list)
        }

        val copies = "发货份数:${dataBean.num}"
        headerView.text_copies.text = copies
        headerView.text_title.text = dataBean.projectName
        when (dataBean.deliveryStatus) {
            1 -> {
                headerView.text_status.text = "待发货"
                btn_delete_order.visibility = View.GONE
                btn_order_remind.visibility = View.VISIBLE
                btn_order_confirm_receipt.visibility = View.GONE

                text_express_delivery.visibility = View.GONE
                text_express_no.visibility = View.GONE
                text_delivery_time.visibility = View.GONE
            }
            2 -> {
                headerView.text_status.text = "发货中"
                btn_delete_order.visibility = View.GONE
                btn_order_remind.visibility = View.GONE
                btn_order_confirm_receipt.visibility = View.VISIBLE

                setExpressInfo(dataBean)
            }
            3 -> {
                headerView.text_status.text = "已收货"
                btn_delete_order.visibility = View.VISIBLE
                btn_order_remind.visibility = View.GONE
                btn_order_confirm_receipt.visibility = View.GONE

                setExpressInfo(dataBean)
            }
            else -> {
            }
        }

        GlideApp.with(this)
                .load(dataBean.coverUrl)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .placeholder(R.mipmap.icon_default_picture)
                .into(headerView.img_project)

        circleProgress.setMax(100)
        circleProgress.setProgress(100)
        text_first_line.text = "分红"

        if (null != dataBean.marketPriceYuan) {
            val marketPrice = "市场价/份 " + NumberFormatUtils.getInstance().format(dataBean.marketPriceYuan.toDouble()) + "元"
            text_market_price.text = setText(marketPrice, marketPrice.indexOf("份") + 1, marketPrice.length)
        }
        if (null != dataBean.subscribePriceYuan) {
            val subscribePrice = "认购价/份 " + NumberFormatUtils.getInstance().format(dataBean.subscribePriceYuan.toDouble()) + "元"
            text_subscription_price.text = setText(subscribePrice, subscribePrice.indexOf("份") + 1, subscribePrice.length)
        }

        headerView.text_name.text = dataBean.contacts
        headerView.text_phone.text = dataBean.contactNumber
        headerView.text_address.text = dataBean.addressDetail
        footerView.text_remark.text = dataBean.remark
    }

    private fun setExpressInfo(dataBean: ProjectDeliveryDetailResp.DataBean?) {
        text_express_delivery.visibility = View.VISIBLE
        text_express_no.visibility = View.VISIBLE
        text_delivery_time.visibility = View.VISIBLE

        val expressDelivery = "快递公司: " + dataBean!!.expressCompanyName
        text_express_delivery.text = expressDelivery

        val expressNo = "快递单号: " + dataBean.expressNo
        text_express_no.text = expressNo

        val deliveryTime = "发货时间: " + dataBean.deliveryTime
        text_delivery_time.text = deliveryTime
    }

    private fun setText(text: String, start: Int, end: Int): SpannableString {
        val spanString = SpannableString(text)
        //再构造一个改变字体颜色的Span
        val span = ForegroundColorSpan(ContextCompat.getColor(this, R.color.aid_prompt_color))
        //将这个Span应用于指定范围的字体
        spanString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val span1 = AbsoluteSizeSpan(15, true)
        spanString.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spanString
    }

    override fun loadFailure() {
        Timber.e("loadFailure")
    }

    override fun deleteSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "删除订单成功！！！")
        finish()
    }

    override fun deleteFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun remindSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "提醒成功！！！")
    }

    override fun remindFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun confirmReceiptSuccess(dataBean: ProjectLogisticsResp.DataBean?) {
        ToastUtil.showTip(this, "确认收货成功！！！")
    }

    override fun confirmReceiptFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }
}
